#pragma once
#include <grpcpp/grpcpp.h>
#include "message.grpc.pb.h"
#include "message.pb.h"
#include <condition_variable>
#include <mutex>
#include <queue>
#include "Singleton.h"
//连接池类
class StatusConnectionPool
{

public:
    StatusConnectionPool(std::size_t poolSize,const std::string& host,const std::string& port)
    :b_stop_(false)
    ,poolSize_(poolSize)
    ,host_(host)
    ,port_(port)
    {
        std::shared_ptr<grpc::Channel> channel = grpc::CreateChannel(host_+":"+port_,grpc::InsecureChannelCredentials());
        //建立连接
        for(int i =0;i<poolSize_;i++)
        {
            //创建连接
            std::unique_ptr<message::StatusServer::Stub> stub = message::StatusServer::NewStub(channel);
            connections_.push(std::move(stub));
        }
    }
    //获取连接
    std::unique_ptr<message::StatusServer::Stub> GetConnection()
    {
        std::unique_lock<std::mutex> lock(mtx_);
        cond_.wait(lock,[this](){
            return !connections_.empty()||b_stop_;
        });
        if(b_stop_)
        {
            return nullptr;
        }
        std::unique_ptr<message::StatusServer::Stub> stub = std::move(connections_.front());
        connections_.pop();
        return stub;
    }

    void ReturnConnection(std::unique_ptr<message::StatusServer::Stub> stub)
    {
        std::unique_lock<std::mutex> lock(mtx_);
        if (b_stop_)
        {
            return;
        }
        connections_.push(std::move(stub));
        cond_.notify_one();

    }
    void Stop()
    {
        std::unique_lock<std::mutex> lock(mtx_);
        b_stop_ = true;
        cond_.notify_all();
        while(!connections_.empty())
        {
            connections_.pop();
        }
    }
    ~StatusConnectionPool()
    {
        Stop();

    }
    


private:
    //不同rpc的stub位于 pack::Service::Stub
    std::queue<std::unique_ptr<message::StatusServer::Stub>> connections_;
    std::mutex mtx_;
    std::condition_variable cond_;
    bool b_stop_;
    std::size_t poolSize_;
    std::string host_;
    std::string port_;

};

class StatusGrpcClient:public Singleton<StatusGrpcClient>
{
    friend class Singleton<StatusGrpcClient>;
//公有方法
public:
    ~StatusGrpcClient()
    { 
    }
    message::GetChatServerResponse GetChatServer(int uid);

//私有方法
private:
    StatusGrpcClient();
    
//私有属性
private:
    std::unique_ptr<StatusConnectionPool> pool_;
};